<?php
/**
 * TokenLogic.php
 * @author pingo
 * @date 2022/6/10 8:54
 */

namespace app\logic;

use think\facade\Cache;

class TokenLogic
{
    /**
     * token生成
     *
     * @param $uid
     * @param $expired
     * @return array
     * @author pingo
     * @date 2022/6/10 9:18
     */
    public static function make($uid, $expired = 86400)
    {
        $token = md5(time() . $uid . mt_rand(100, 999));
        $refresh_token = md5($token);
        Cache::set($token, $uid, $expired);
        Cache::set($refresh_token, $uid, $expired + 7200);
        return [
            "token"         => $token,
            "refresh_token" => $refresh_token,
        ];
    }

    /**
     * 刷新token
     *
     * @param $fresh_token
     * @return array|false
     * @author pingo
     * @date 2022/6/10 9:18
     */
    public static function refresh($fresh_token)
    {
        $uid = Cache::get($fresh_token);
        if ($uid){
            return self::make($uid, 86400);
        }
        return false;
    }

    /**
     * 获取用户UID
     *
     * @param $token
     * @return int
     * @author pingo
     * @date 2022/6/10 9:19
     */
    public static function getUserID($token)
    {
        $uid = Cache::get($token);
        if ($uid){
            return intval($uid);
        }
        return 0;
    }

    public static function Remove($token)
    {
        Cache::delete($token);
    }
}